requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        task:"../common/task",
        md5: 'md5.min'
    }
});
requirejs(['jquery', 'pageJs','config', 'arttemplateUtil','common','task','md5','account','validform','wdatePicker'], function($, pageJs,config, arttemplateUtil,common,task,md5,account) {
	
	var param = {};
	var account_tpl;//账号列表模板
	var roleList;//角色列表
	
	var getData = function(){
		var index = common.loading();
		var count;
		common.common_ajax_request('/api/seller/v1/queryAccountList',param,false,function(data,code,msg){
			if(msg.businessCode==0){
				setData(data);
				pageJs.setPage(data.pageNo,data.totalPage,data.totalCount,callback);			
			}else{
				setData({});
				window.layer.msg("系统异常");
			}
			layer.close(index); //关闭加载层
		},"","post");
	}
	
	var initTpl = function(){
		account_tpl = arttemplateUtil.template.compile($.setHTML('authority/templates/account_list_tpl.html'));
	}
	
	//账户列表
	var setData = function(data){
		var res = {
				records:data.records
		}
		$("#account_tpl").html(account_tpl(res));
	}
	
	var callback = function(page){
		param.pageNo=page;
		getData();
	}
	
	var init = function() {
		initTpl();
		getData();
		initRoleData($('#role'),'全部');
		openAddAccountWindow();
		initListBtn();
	};
	
	//查询
   $('.serchBtn').on('click',function(){
	   param.pageNo=1;
	   $.each($('#serchForm').serializeArray(), function(i, item) {
			if(item.value==""){
				delete param[item.name]
			}else{
				param[item.name]=item.value;
			}
		})
		getData();
	});
   
	//重置
	$('.resetBtn').on('click',function(){
		$.each($('#serchForm').serializeArray(), function(i, item) {
			delete param[item.name];
		});
		$("form[name=serchForm]")[0].reset();
		$("#serchForm input").removeClass("Validform_error");
		$("#serchForm .Validform_checktip").removeClass("Validform_wrong").html("");
		getData();
	});
	
	//导出
	$('.excelBtn').on('click',function(){
		$("#excel").attr("action",config.apiRoot()+"/api/seller/v1/exportAccountList");
		var html = [];
		$.each($('#serchForm').serializeArray(), function(i, item) {
			html.push("<input name=\""+item.name+"\" type='hidden' id=\""+item.name+"\" value=\""+item.value+"\" />");
		});
		$.each(config.setFullParameterArr({}), function(i, item) {
			html.push("<input name=\""+i+"\" type='hidden' id="+i+" value=\""+item+"\" />");
		});
		$("#excel").html(html.join(""));
		$("#excel").submit();
	});
	
	/***********************************************点击删除按钮删除账户*********************************/
	var delAccount = function() {
		$("#account_tpl").off('click','.accout_del_btn').on('click','.accout_del_btn',function(){
			//获取账户id
			var account_id = $(this).attr("data-id");
			var userName = $(this).attr("data-username");
			layer.confirm('确定删除吗？', {
				  btn: ['确定','取消']
			}, function(){
				var param = {accountId: account_id, userName: userName};
				common.common_ajax_request('/api/seller/v1/delAccount',param,false,function(data,code,msg){
					if(msg.businessCode==0){
						/*if(data.businessCode == 100117){
							layer.alert('账号目前有关联操作，无法进行删除！');
						}else{*/
						
							layer.msg("删除成功！");
							getData();
						//}
					}else{
						layer.msg(data.businessNote);
					}
				},"","post");
			}, function(){});
			
			return false;
			
		});
		
	}
	
	/***********************************************点击暂停和使用按钮*********************************/
	var updateAccountStatus = function() {
		$("#account_tpl").off('click','.status_btn').on('click','.status_btn',function(){
			//获取账户id
			var account_id = $(this).attr("data-id");
			var userName = $(this).attr("data-username");
			var $upThis = $(this);
			//0:正常，1：停用
			var status = 0;
			if($upThis.parent().find(".typetext").text()=="使用中"){
				status = 1;
			}
			var param = {accountId: account_id,status:status, userName: userName};
			//调用更新状态接口更新账户状态
			common.common_ajax_request('/api/seller/v1/updateAccountStatus',param,false,function(data,code,msg){
				if(msg.businessCode==0){
					if(status == 1) {
						//停用状态
						layer.msg('停用成功', {time:1000,icon: 1});
						$upThis.html("<i class='iconfont'>&#xe61e;</i>");
						$upThis.parent().find(".typetext").html("停用中");
					} else {
						//使用状态
						layer.msg('启用成功', {time:1000,icon: 1});
						$upThis.html("<i class='iconfont'>&#xe6c2;</i>");
						$upThis.parent().find(".typetext").html("使用中");
					}
				}else{
					layer.msg(data.businessNote);
				}
			},"","post");
			
			return;
			
		});
		
	}
	
	/***********************************************初始化角色下拉框数据*********************************/
	var initRoleData = function($obj,text) {
		common.common_ajax_request('/api/seller/v1/getRoleListByUserId',param,false,function(data,code,msg){
			if(msg.businessCode==0){
				//存放数据
				roleList = data;
				appendOption($obj,roleList,text);
			}else{
				layer.msg(data.businessNote);
			}
		});
	}
	
	//遍历数据,往下拉框添加数据
	var appendOption = function($obj,data,text) {
		$obj.find("option").remove(); 
		$obj.append("<option value=''>" + text + "</option>"); 
		$.each(data, function(idx, item) {
			$obj.append("<option value="+item.id+">"+item.ro_name+"</option>");
		});
	};
	
	/********************************************点击新增按钮 新增账户信息***********************************/
	
	var add_account_frm_valid = $("#addAccoutForm").Validform({
		tiptype:4,
		isShowRight:false
	});
	
	var openAddAccountWindow = function() {
		
		//点击创建账户按钮
		$('.create_account_btn').on("click",function(){
			
			$("form[name=addAccoutForm]")[0].reset();
			
			$('#addAccoutForm').find('input[name=plat_label]').val(config.sysconfig().plat_label);
			
			//判断角色的option长度，如果〈=1，则加载内容
			if($('#addAccoutForm').find('select[name=role] option').length <= 1) {
				appendOption($('#addAccoutForm').find('select[name=role_id]'),roleList,'请选择');
			}
			
			task.openWindow("#addAccount","#save_account_btn",function() {
				//确认按钮响应事件
				if(add_account_frm_valid.check()) {
					 	//进度
					    var tipLoading = window.layer.load(1, {
						  shade: [0.1,'#fff'] //0.1透明度的白色背景
						});
						
						$("#save_account_btn").attr('disabled',true);
						var param = $('#addAccoutForm').serializeArray();
						//将密码加密
						var userPassword = $.trim($('#addAccoutForm').find('input[name=userPassword]').val());
						if(userPassword != undefined && userPassword != null && userPassword != '') {
							param.push({"name":"md5Password","value":md5($.trim(userPassword))});
						}
						
						var role_name = $('#addAccoutForm').find('select[name=role_id]').find('option:selected').text();
						param.push({"name":"role_name","value":role_name});
						common.common_ajax_request('/api/seller/v1/saveOrUpAccount',param, false, function(data,code,msg){
							
							$("#addAccount").modal('hide'); 
							getData();
						},'','post',function(){
							$("#save_account_btn").removeAttr('disabled');
							window.layer.close(tipLoading);
						});
					
			     } 
			},"#save_account_cancel_btn",function(){
				add_account_frm_valid.resetForm();
			});
		});
		
		$('.add_close').on("click",function(){
			add_account_frm_valid.resetForm();
		});
		
	}
	
	/********************************************点击编辑按钮 编辑账户信息*********************************/
	
	var edit_account_frm_valid = $("#editAccoutForm").Validform({
		tiptype:4,
		isShowRight:false
	});
	
	
	
	//判断select中是否存在值为value的项  
	var isExistOption = function($obj,value) {  
	    var isExist = false;  
	    var count = $obj.find('option').length;     
	    for(var i=0;i<count;i++) {     
	         if($obj.get(0).options[i].value == value){     
	             isExist = true;     
	             break;     
	         }     
	    }     
	    return isExist;  
	}  
	
	
	var openEditAccountWindow = function() {
		
		$(document).off('click','.accout_edit_btn').on('click','.accout_edit_btn',function() {
			
			edit_account_frm_valid.resetForm();
			
			//判断角色的option长度，如果〈=1，则加载内容
			if($('#editAccoutForm').find('select[name=role] option').length <= 1) {
				appendOption($('#editAccoutForm').find('select[name=role_id]'),roleList,'请选择');
			}
			
			$this = $(this);
			//设置账户id值
			$("#editAccoutForm").find('input[name=id]').val($this.attr('data-id'));
			//设置账户名称
			$("#editAccoutForm").find('input[name=userName]').val($this.parents('tr').children().eq(1).html());
			$("#editAccoutForm").find('input[name=userName1]').val($this.parents('tr').children().eq(1).html());
			//设置姓名
			$("#editAccoutForm").find('input[name=trueName]').val($this.parents('tr').children().eq(2).html());
			//设置联系方式
			//$("#editAccoutForm").find('input[name=mobile]').val($this.parents('tr').children().eq(3).html());
			//设置邮箱
			//$("#editAccoutForm").find('input[name=email]').val($this.parents('tr').children().eq(4).html());
			$("#editAccoutForm").find('input[name=userRole]').removeAttr('checked');
			$("#editAccoutForm").find('input[name=userRole][value='+$this.attr('data-userRole')+']').attr('checked','checked');
			//设置角色值
			var role_id = $this.attr('data-role-id');
			var $role = $("#editAccoutForm").find('select[name=role_id]');
			if(isExistOption($role,role_id)) {
				$role.val(role_id);
			}
			
			//设置员工号
			$("#editAccoutForm").find('input[name=staff_no]').val($this.attr('data-staff-no'));
			
			task.openWindow("#editAccount","#edit_account_btn",function() {
				//确认按钮响应事件
				if(edit_account_frm_valid.check()) {
					    //进度
					    var tipLoading = window.layer.load(1, {
						  shade: [0.1,'#fff'] //0.1透明度的白色背景
						});
					   
						$("#edit_account_btn").attr('disabled',true);
						var param = $('#editAccoutForm').serializeArray();
						//获取新密码加密
						var userPassword = $.trim($('#editAccoutForm').find('input[name=userPassword]').val());
						if(userPassword != undefined && userPassword != null && userPassword != '') {
							param.push({"name":"md5Password","value":md5($.trim(userPassword))});
						}
						
						var role_name = $('#editAccoutForm').find('select[name=role_id]').find('option:selected').text();
						param.push({"name":"role_name","value":role_name});
						
						common.common_ajax_request('/api/seller/v1/saveOrUpAccount',param, false, function(data,code,msg){
							$("#editAccount").modal('hide'); 
							getData();
						},'','post',function(){
							$("#edit_account_btn").removeAttr('disabled');
							window.layer.close(tipLoading);
						});
					
			     } 
			},"#edit_account_cancel_btn",function(){
				edit_account_frm_valid.resetForm();
			});
			
		});
		
		$('.edit_close').on("click",function(){
			edit_account_frm_valid.resetForm();
		});
	}
	
	//初始化列表按钮
	var initListBtn = function() {
		delAccount();
		updateAccountStatus();
		openEditAccountWindow();
	}
	
   init();
});
